import { MenuOutlined } from '@ant-design/icons';
import { Table, Checkbox, Modal, Button, Col, InputNumber, Row, Slider } from 'antd';
import { arrayMoveImmutable } from 'array-move';
import React, { useState, useEffect } from 'react';
import './sortable.css'
import { createFromIconfontCN } from '@ant-design/icons';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});
Storage = window.localStorage
/**
 * @param {array} tableColum  列头数据  例如 const coloumArray=[{ title: "序号", key: "xuhao",show:true}]
 * @param {Function} handleTableColum 这个就是处理列表数据的函数
 * @param {string} stroageName 本地仓库变量名称
 * @param {number} initSize 初始大小
 * @param {Function}  handleIntisize 这个就是处理初始table大小的函数
 * @param {*} props 
 * @returns 
 */
const Sortable_width = (props) => {
  const [tableColoumList, setTableColoumList] = useState([])
  const [isModalOpen, setIsModalOpen] = useState();
  const [inputValue, setInputValue] = useState(props.initSize ? parseFloat(props.initSize) : 1);
  useEffect(() => {
    const data = []
    if (Storage[props.storageName]) {
      var arr = JSON.parse(Storage[props.storageName])
      var result = false
      if (arr.length === props.tableColnum.length) {
        let isSame = (obj1, obj2) => obj1.key === obj2.key;
        result = props.tableColnum.every(obj1 => {
          return arr.find(obj2 => isSame(obj1, obj2)) !== undefined;
        });
      } else { result = false }
  
      if (result) {
        props.tableColnum.forEach(obj1 => {
          let obj2 = arr.find(obj => obj.key === obj1.key);
          if (obj2) {
            obj2.title = obj1.title;// 这里将array2中对应对象的值修改为array1中对象的值
            if (obj1.style) {
              obj2.style = obj1.style;
            }
          }
        });
        // //console.log("有本地存储且长度一样", arr)
        for (let i = 0; i < arr.length; i++) {
          let item = { ...arr[i], index: i }
          data.push(item)
        }
        // //console.log("有本地存储且长度一样", data)
        Storage[props.storageName] = JSON.stringify(data)
      } else {
        arr.forEach(obj1 => {
          let obj2 = props.tableColnum.find(obj => obj.key === obj1.key);
          if (obj2) {
            obj2 = obj1; // 这里将array2中对应对象的值修改为array1中对象的值  
          }
        });
        // //console.log("无本地存储且长度一样", props.tableColnum)
        for (let i = 0; i < props.tableColnum.length; i++) {
          let item = { ...props.tableColnum[i], index: i }
          data.push(item)
        }
        // //console.log("有本地存储且长度不一样", data)
        Storage[props.storageName] = JSON.stringify(data)
        props.handleTableColomn(data)
      }
  
    } else {
      // //console.log("无本地存储",props.tableColnum)
      Storage[props.storageName] = JSON.stringify(props.tableColnum)
      for (let i = 0; i < props.tableColnum.length; i++) {
        let item = { key: props.tableColnum[i].key, title: props.tableColnum[i].title, show: true, index: i }
        data.push(item)
      }
    }
    setDataSource(data)
  }, [props.tableColnum])
  useEffect(() => {
    setIsModalOpen(props.open)
  }, [props.open])
  useEffect(() => {
    setInputValue(props.initSize)
  }, [props.initSize])

  const [dataSource, setDataSource] = useState();

  const DragHandle = SortableHandle(() => (
    <MenuOutlined
      style={{
        cursor: 'grab',
        color: '#999',
      }}
    />
  ));

  const SortableItem = SortableElement((props) => <tr {...props} />);
  const SortableBody = SortableContainer((props) => <tbody {...props} />);

  const DraggableContainer = (props) => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={onSortEnd}
      {...props}
    />
  );
  const onSortEnd = ({ oldIndex, newIndex }) => {
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(dataSource.slice(), oldIndex, newIndex).filter(
        (el) => !!el,
      );

      var resultdata = newData.map(obj => {
        if (obj.show) {
          return { ...obj };
        } else return obj
      })
      var filterdata = resultdata.filter(item => item.show === true)
      props.handleTableColomn(filterdata)
      Storage[props.storageName] = JSON.stringify(newData)
      setDataSource(newData);
    }
  };
  const onChange = (e, record) => {
    var changedList = dataSource.map(obj => {
      if (obj.key === record.key) {
        return { ...obj, show: !record.show };
      } else {
        return obj;
      }
    })
    setDataSource(changedList)
    // var filterdata = changedList.filter(item =>
    //   item.show === true
    // )
    Storage[props.storageName] = JSON.stringify(changedList)
    props.handleTableColomn(changedList)
  };

  const handleClick = () => {
    var changedList = dataSource.map(obj => {
      return { ...obj, show: true }
    })
    setDataSource(changedList)
    Storage[props.storageName] = JSON.stringify(changedList)
    props.handleTableColomn(changedList)
  }
  const columns = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
      className: 'drag-visible',
      render: () => <DragHandle />,
    },
    {
      title: '列名称',
      dataIndex: 'title',
      className: 'drag-visible',
    },
    {
      title: <div>是否显示   <Button onClick={handleClick} type='primary' size='small'>全选</Button></div>,
      dataIndex: 'show',
      render: (text, record, index) => <Checkbox onChange={e => { onChange(e, record) }} checked={text}></Checkbox>,
    }
  ];

  const handleOk = () => {
     setIsModalOpen(false)
  };
  const handleCancel = () => {
      setIsModalOpen(false)
  };

  const showModal = () => {
    setIsModalOpen(true);
  };

  const onSliderChange = (newValue) => {
    newValue == null ? newValue = 1 : ""
    props.handleInitSize(newValue)
  };

  const DraggableBodyRow = ({ className, style, ...restProps }) => {
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = dataSource.findIndex((x) => x.index === restProps['data-row-key']);
    return <SortableItem index={index} {...restProps} />;
  };

  return (
    <>
      <IconFont type="setting" style={props.style?props.style:{}} onClick={showModal} />
      <Modal title="动态列设置" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        {props.initSize && (<Row style={{ marginBottom: 10 }} align="middle">
          <Col span={4}>
            <span>表格宽度</span>
          </Col>
          <Col span={12}>
            <Slider
              min={0.4}
              max={1.4}
              onChange={onSliderChange}
              value={inputValue}
              step={0.01}
            />
          </Col>
          <Col span={4}>
            <InputNumber
              min={0.4}
              max={1.4}
              style={{
                margin: '0 16px',
              }}
              step={0.01}
              value={inputValue}
              onChange={onSliderChange}
            />
          </Col>
        </Row>)}
        <Table
          pagination={false}
          dataSource={dataSource}
          columns={columns}
          rowKey="index"
          components={{
            body: {
              wrapper: DraggableContainer,
              row: DraggableBodyRow,
            },
          }}
        />
      </Modal>
    </>

  );
};
export default Sortable_width;